import json
import os
import time
import traceback

import requests

from util import while_input, is_int_between, cities_file_path


def init_cities():
    """爬取并缓存城市数据"""
    if not os.path.exists(cities_file_path):
        print("正在下载城市数据")
        res=requests.get("https://j.i8tq.com/weather2020/search/city.js").text.replace("var","").replace("=","").replace('city_data','')
        with open(cities_file_path,'w') as f:
            f.write(res)
        cities=json.loads(res)
    with open(cities_file_path,'r') as f:
        cities=json.load(f)

    for index,provence in enumerate(cities):
        print(f"{index}:{provence}")
    num =int( while_input("请输入省级查询的序号:", is_int_between,(0,len(cities.items())-1)))
    provence=list(cities.items())[num][1]
    for index,city in enumerate(provence):
        print(f"{index}:{city}")

    num =int( while_input("请输入市级查询的序号:", is_int_between,(0,len(provence.items())-1)))
    city=list(provence.items())[num][1]
    for index,distinct in enumerate(city):
        print(f"{index}:{distinct}")
    num =int( while_input("请输入区级查询的序号:", is_int_between,(0,len(city.items())-1)))
    distinct=list(city.items())[num][1]
    return distinct['AREAID'],distinct['NAMECN']


def get_days( area_id, name,cookies):
    h={
        "Cookie":cookies,
        "Referer":"https://www.weather.com.cn/",
        'Host':'d1.weather.com.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
    }
    data_file=f"data/{name}_{area_id}.json"
    if os.path.exists(data_file):
        with open(data_file) as f:
            return json.load(f)
    try:
        t=int(time.time() * 1000)
        res=requests.get(f"https://d1.weather.com.cn/calendar_new/2025/{area_id}_202507.html?_={t}",headers=h,allow_redirects=True)
        res.encoding = res.apparent_encoding
        days=res.text.split("=")[1]
        json_data=json.loads(days)
        with open(data_file, "w") as f:
            f.write(days)
        return json_data
    except Exception:
        print("获取失败")
        traceback.print_exc()
        return None
